<template>
    <div class="online-plan-page">
        
        <el-card class="filter-card" shadow="never">
            <div class="filter-row">
                <el-form :inline="true" :model="filters" class="filter-form">
                <el-form-item label="任务名称">
                    <el-input v-model="filters.RequirementNames" placeholder="输入任务名称" clearable style="width: 220px;" @keyup.enter="applyFilters" />
                </el-form-item>

                <el-form-item label="项目名称">
                    <el-select
                        v-model="filters.iIId"
                        filterable
                        clearable
                        remote
                        reserve-keyword
                        :remote-method="remoteSearchProjects"
                        :loading="projectLoading"
                        placeholder="请选择项目名称"
                        style="width: 220px;"
                    >
                        <el-option
                            v-for="opt in projectOptions"
                            :key="opt.value"
                            :label="opt.label"
                            :value="opt.value" />
                    </el-select>
                </el-form-item>

                <el-form-item label="上线时间">
                    <el-date-picker
                        v-model="filters.playOnlineTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        format="YYYY-MM-DD"
                        :clearable="true"
                        @change="onPlayOnlineTimeChange"
                        placeholder="选择日期"
                    />
                </el-form-item>

                <el-form-item label="项目经理">
                    <el-input v-model="filters.managerName" placeholder="输入项目经理" clearable style="width: 180px;" @keyup.enter="applyFilters" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="applyFilters">
                        <el-icon class="btn-icon"><Search /></el-icon>
                        查询
                    </el-button>
                    <el-button @click="resetFilters">
                        <el-icon class="btn-icon"><Refresh /></el-icon>
                        重置
                    </el-button>
                </el-form-item>
                </el-form>
                <el-button type="primary" @click="openCreate" class="create-btn">
                    <el-icon class="btn-icon"><Plus /></el-icon>
                    新增计划
                </el-button>
            </div>
        </el-card>

        

        <el-card class="table-card" shadow="never">
            <template v-if="plans.length > 0">
            <el-table :data="plans" stripe v-loading="loading">
                <el-table-column prop="title" label="上线需求" min-width="320">
                    <template #default="scope">
                        <div class="title-cell">
                            <span class="title-text" @click.stop="openDetail(scope.row)">{{ scope.row.title }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="systemName" label="项目名称" width="140" />
                <el-table-column prop="version" label="项目经理" width="120" />
                <el-table-column prop="plannedDate" label="计划上线时间" width="140">
                    <template #default="scope">
                        <span>{{ formatDate(scope.row.plannedDate) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="备注" min-width="220" show-overflow-tooltip>
                    <template #default="scope">
                        <span>{{ scope.row.tipMsg || '-' }}</span>
                    </template>
                </el-table-column>
                
                <el-table-column prop="updatedAt" label="更新时间" width="170">
                    <template #default="scope">
                        <span>{{ formatDateTime(scope.row.updatedAt) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="220" fixed="right">
                    <template #default="scope">
                        <el-button link type="primary" @click="openEdit(scope.row)">
                            <el-icon><EditPen /></el-icon>
                            编辑
                        </el-button>
                        <el-button link type="danger" @click="confirmRemove(scope.row)">
                            <el-icon><Delete /></el-icon>
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="table-footer">
                <el-pagination
                    background
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalCount"
                    :page-sizes="[10, 20, 50]"
                    v-model:page-size="pageSize"
                    v-model:current-page="currentPage"
                    @size-change="fetchPlanList"
                    @current-change="fetchPlanList"
                />
            </div>
            </template>
            <el-empty v-else description="暂无数据" :image-size="100" />
        </el-card>

        <el-drawer v-model="detailVisible" :title="detailPlan?.title || '计划详情'" size="50%">
            <div v-if="detailPlan" class="detail-wrap">
                <el-descriptions :column="2" border>
                    <el-descriptions-item label="上线需求">{{ detailPlan.title }}</el-descriptions-item>
                    <el-descriptions-item label="项目名称">{{ detailPlan.systemName || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="项目经理">{{ detailPlan.version || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="计划上线时间">{{ formatDate(detailPlan.plannedDate) }}</el-descriptions-item>
                    <el-descriptions-item label="更新时间">{{ formatDateTime(detailPlan.updatedAt) }}</el-descriptions-item>
                    <el-descriptions-item label="创建时间">{{ formatDateTime(detailPlan.createdAt) }}</el-descriptions-item>
                </el-descriptions>

                

                <el-divider>备注</el-divider>
                <div class="pre-text">{{ detailPlan.remark || '—' }}</div>
            </div>
        </el-drawer>

        <el-dialog v-model="editVisible" :title="editForm.id ? '编辑计划' : '新增计划'" width="720px" align-center append-to-body class="center-dialog">
            <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="96px">
                <el-row :gutter="16">
                    <el-col :span="24">
                        <el-form-item label="上线需求" prop="title">
                            <el-input
                                v-model="editForm.title"
                                type="textarea"
                                :autosize="{ minRows: 2, maxRows: 6 }"
                                placeholder="可多行输入，每行一个上线需求"
                                maxlength="2000"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="项目名称">
                            <el-select
                                v-model="editForm.systemName"
                                filterable
                                remote
                                reserve-keyword
                                :remote-method="remoteSearchProjects"
                                :loading="projectLoading"
                                placeholder="请选择项目名称">
                                <el-option
                                    v-for="opt in projectOptions"
                                    :key="opt.value"
                                    :label="opt.label"
                                    :value="opt.label" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    
                    <el-col :span="12">
                        <el-form-item label="上线日期" prop="plannedDate">
                            <el-date-picker v-model="editForm.plannedDate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" />
                        </el-form-item>
                    </el-col>
                    
                    
                    <el-col :span="24">
                        <el-form-item label="备注">
                            <el-input v-model="editForm.remark" type="textarea" :rows="2" placeholder="补充说明" />
                        </el-form-item>
                    </el-col>
                    
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editVisible = false">取消</el-button>
                    <el-button type="primary" :loading="submitLoading" @click="submitEdit">保存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
    
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'
import { Plus, Search, Refresh, EditPen, Delete } from '@element-plus/icons-vue'
import { GetItemList, createOnlinePlan, getOnlinePlanList, updateOnlinePlan, deleteOnlinePlan } from '@/api/newDemands/index'

// 已移除状态/风险/环境类型

interface OnlinePlanItem {
    id: string
    title: string
    systemName?: string
    version?: string
    plannedDate: string
    
    
    remark?: string
    tipMsg?: string
    createdAt: string
    updatedAt: string
}

 

// const STORAGE_KEY = 'onlinePlans'

const loading = ref(false)
const plans = ref<OnlinePlanItem[]>([])
const totalCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
// 批量新增模式已移除

const filters = reactive({
    RequirementNames: '',
    iIId: '' as string | number,
    playOnlineTime: '',
    managerName: ''
})

const editVisible = ref(false)
const editFormRef = ref<FormInstance>()
const submitLoading = ref(false)
const editForm = reactive<OnlinePlanItem>({
    id: '',
    title: '',
    systemName: '',
    version: '',
    plannedDate: '',
    
    remark: '',
    createdAt: '',
    updatedAt: ''
})

const rules: FormRules = {
    title: [{ required: true, message: '请输入上线需求', trigger: 'blur' }],
    plannedDate: [{ required: true, message: '请选择计划上线时间', trigger: 'change' }]
}

const detailVisible = ref(false)
const detailPlan = ref<OnlinePlanItem | null>(null)

// 项目下拉（远程搜索）
interface ProjectOption { value: string; label: string }
const projectOptions = ref<ProjectOption[]>([])
const allProjectOptions = ref<ProjectOption[]>([])
const projectLoading = ref(false)
async function fetchAllProjects() {
    projectLoading.value = true
    try {
        const { data } = await GetItemList()
        if (data.code === 200) {
            const list = (data.data || []).map((item: any) => ({ value: String(item.ID), label: item.itemName }))
            allProjectOptions.value = [...list]
            projectOptions.value = [...list]
        } else {
            ElMessage.error(data.msg || '获取项目列表失败')
        }
    } finally {
        projectLoading.value = false
    }
}

function remoteSearchProjects(query: string) {
    if (!query) {
        // 显示全部
        projectOptions.value = [...allProjectOptions.value]
        return
    }
    const lower = query.toLowerCase()
    projectOptions.value = allProjectOptions.value.filter(opt => opt.label.toLowerCase().includes(lower))
}

// 项目经理下拉（远程搜索）
 

function openDetail(row: OnlinePlanItem) {
    detailPlan.value = { ...row }
    detailVisible.value = true
}

function openCreate() {
    Object.assign(editForm, {
        id: '',
        title: '',
        systemName: '',
        version: '',
        plannedDate: '',
        remark: '',
        createdAt: '',
        updatedAt: ''
    })
    // 每次打开新建，都刷新项目下拉数据
    fetchAllProjects()
    editVisible.value = true
}

function openEdit(row: OnlinePlanItem) {
    Object.assign(editForm, row)
    fetchAllProjects()
    editVisible.value = true
}


function submitEdit() {
    if (!editFormRef.value) return
    editFormRef.value.validate(async (valid) => {
        if (!valid) return
        submitLoading.value = true
        try {
            if (!editForm.id) {
                const names = (editForm.title || '')
                    .split('\n')
                    .map(s => s.trim())
                    .filter(s => s.length > 0)
                if (names.length === 0) {
                    ElMessage.error('请输入上线需求')
                    return
                }
                // 校验项目与日期
                if (!editForm.systemName) {
                    ElMessage.error('请选择项目名称')
                    return
                }
                if (!editForm.plannedDate) {
                    ElMessage.error('请选择上线日期')
                    return
                }
                // 组装接口参数并调用创建上线计划
                const selected = projectOptions.value.find(opt => opt.label === editForm.systemName)
                const iIId = selected ? Number(selected.value) : 0
                const playOnlineTime = (editForm.plannedDate || '').replace(/-/g, '/')
                const payload = {
                    RequirementNames: names,
                    iIId,
                    playOnlineTime,
                    tipMsg: editForm.remark || ''
                }
                const res = await createOnlinePlan(payload as any)
                if (!(res && res.data && res.data.code === 200)) {
                    ElMessage.error((res && res.data && res.data.msg) || '创建上线计划失败')
                    return
                }
                await fetchPlanList()
            } else {
                // 编辑：调用更新接口
                if (!editForm.systemName) {
                    ElMessage.error('请选择项目名称')
                    return
                }
                if (!editForm.plannedDate) {
                    ElMessage.error('请选择上线日期')
                    return
                }
                const selected = projectOptions.value.find(opt => opt.label === editForm.systemName)
                const iIId = selected ? Number(selected.value) : 0
                const playOnlineTime = (editForm.plannedDate || '').replace(/-/g, '/')
                const payload = {
                    id: Number(editForm.id),
                    RequirementNames: editForm.title || '',
                    iIId,
                    playOnlineTime,
                    managerName: editForm.version || '',
                    tipMsg: editForm.remark || ''
                }
                const res = await updateOnlinePlan(payload as any)
                if (!(res && res.data && res.data.code === 200)) {
                    ElMessage.error((res && res.data && res.data.msg) || '更新上线计划失败')
                    return
                }
                await fetchPlanList()
            }
            editVisible.value = false
            ElMessage.success('保存成功')
        } finally {
            submitLoading.value = false
        }
    })
}

async function removePlan(id: string) {
    const numId = Number(id)
    if (!numId) {
        ElMessage.error('ID无效')
        return
    }
    const { data } = await deleteOnlinePlan(numId)
    if (data && data.code === 200) {
        ElMessage.success('已删除')
        fetchPlanList()
    } else {
        ElMessage.error(data?.msg || '删除失败')
    }
}

function confirmRemove(row: OnlinePlanItem) {
    ElMessageBox.confirm(
        `确认删除【${row.title}】？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    )
    .then(() => removePlan(row.id))
    .catch(() => {})
}

async function fetchPlanList() {
    loading.value = true
    try {
        const playOnlineTime = (filters.playOnlineTime || '').replace(/-/g, '/')
        const params = {
            RequirementNames: filters.RequirementNames || '',
            iIId: filters.iIId || '',
            playOnlineTime,
            managerName: filters.managerName || '',
            page: currentPage.value,
            pageSize: pageSize.value
        }
        const { data } = await getOnlinePlanList(params as any)
        if (data.code === 200) {
            const res = data.data
            plans.value = (res?.list || []).map((it: any) => ({
                id: String(it.ID),
                title: it.requirementName,
                systemName: it.itemItemName,
                version: it.managerName,
                plannedDate: it.playOnlineTime,
                remark: it.tipMsg || it.remark || it.tipsMsg || it.tipmsg || '',
                tipMsg: it.tipMsg || it.remark || it.tipsMsg || it.tipmsg || '',
                createdAt: it.createAt,
                updatedAt: it.UpdatedAt
            }))
            totalCount.value = Number(res?.total || 0)
        } else {
            ElMessage.error(data.msg || '获取上线计划失败')
        }
    } finally {
        loading.value = false
    }
}

function applyFilters() {
    currentPage.value = 1
    fetchPlanList()
}

function resetFilters() {
    filters.RequirementNames = ''
    filters.iIId = ''
    filters.playOnlineTime = ''
    filters.managerName = ''
    currentPage.value = 1
    fetchPlanList()
}

function onPlayOnlineTimeChange() {
    currentPage.value = 1
    fetchPlanList()
}
// 批量模式已移除

// 服务端分页，去掉前端分页与本地过滤

// 已改为服务端数据，不再本地保存

// 已切换为服务端分页，移除本地存储加载

onMounted(() => {
    fetchPlanList()
    fetchAllProjects()
})

// 已切换为服务端数据，无需本地ID生成

 

function formatDate(d?: string) {
    if (!d) return '—'
    return d
}

function formatDateTime(d?: string) {
    if (!d) return '—'
    const date = new Date(d)
    if (isNaN(date.getTime())) return d
    const y = date.getFullYear()
    const m = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hh = String(date.getHours()).padStart(2, '0')
    const mm = String(date.getMinutes()).padStart(2, '0')
    return `${y}-${m}-${day} ${hh}:${mm}`
}
</script>

<style scoped>
.center-dialog :deep(.el-dialog) {
    margin: 0 !important;
    left: 50% !important;
    transform: translateX(-50%) !important;
}
.center-dialog :deep(.el-overlay-dialog) {
    display: flex;
    align-items: center;
    justify-content: center;
}
.online-plan-page {
    padding: 12px;
}
.page-header {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-bottom: 12px;
}
.title-wrap {
    display: flex;
    align-items: baseline;
    gap: 12px;
}
.page-title {
    font-size: 20px;
    font-weight: 600;
}
.page-sub {
    color: #909399;
    font-size: 13px;
}
.create-btn .btn-icon {
    margin-right: 4px;
}
 
.filter-card {
    margin-bottom: 12px;
}
.filter-form {
    display: flex;
    flex-wrap: wrap;
}
.filter-row {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 12px;
}
.table-card :deep(.el-table) {
    --el-table-header-bg-color: #fafafa;
}
.table-footer {
    margin-top: 12px;
    display: flex;
    justify-content: flex-end;
}
.title-cell {
    display: flex;
    align-items: center;
    gap: 8px;
}
.title-text {
    color: #409eff;
    cursor: pointer;
}
.title-text:hover {
    text-decoration: underline;
}
 
.sub-line {
    color: #909399;
    font-size: 12px;
}
.sub-line .dot {
    display: inline-block;
    width: 4px;
    height: 4px;
    border-radius: 50%;
    background: #dcdfe6;
    margin: 0 8px;
}
.detail-wrap {
    padding-right: 12px;
}
.pre-text {
    white-space: pre-wrap;
    line-height: 1.7;
}
</style>


